import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useFileDataStore } from './fileData'
import { useWorkspaceStore } from './workspace'
import { findRPCRecordsFromMdbDirectory } from '../config/logPaths'

// RPC记录接口定义
interface RPCRecord {
  serviceName: string
  resourcePath: string
  resourceInterface: string
  method: string
  callCount: number
}

// 服务统计接口
interface ServiceStats {
  name: string
  totalCalls: number
  methods: MethodStats[]
}

// 方法统计接口
interface MethodStats {
  serviceName: string
  resourcePath: string
  resourceInterface: string
  method: string
  callCount: number
  percentage?: string
}

// 趋势数据接口
interface TrendData {
  time: string
  count: number
}

// 依赖节点接口
interface DependencyNode {
  id: string
  name: string
  value: number
  category: number
}

// 依赖链接接口
interface DependencyLink {
  source: string
  target: string
  value: number
}

export const useRPCAnalysisStore = defineStore('rpcAnalysis', () => {
  // 原始RPC数据
  const rpcRecords = ref<RPCRecord[]>([])
  
  // 全局统计数据
  const globalStats = ref({
    totalCalls: 0,
    activeServices: 0,
    activeMethods: 0
  })
  
  // 趋势数据
  const trendData = ref<TrendData[]>([])
  
  // 服务排行榜数据
  const serviceLeaderboard = ref<ServiceStats[]>([])
  
  // 热门方法数据
  const hotMethods = ref<MethodStats[]>([])
  
  // 依赖关系数据
  const dependencyNodes = ref<DependencyNode[]>([])
  const dependencyLinks = ref<DependencyLink[]>([])
  
  // 标识是否使用模拟数据
  const isUsingMockData = ref(false)
  
  // 计算属性：所有服务列表
  const allServices = computed(() => {
    const services = new Set(rpcRecords.value.map(record => record.serviceName))
    return Array.from(services).map(name => ({ name }))
  })
  
  // 计算属性：所有方法列表
  const allMethods = computed(() => {
    return rpcRecords.value.map(record => ({
      serviceName: record.serviceName,
      methodName: record.method
    }))
  })
  
  // 解析RPC日志文件
  const parseRPCLogFile = (content: string): RPCRecord[] => {
    const lines = content.split('\n').filter(line => line.trim())
    const records: RPCRecord[] = []
    
    for (const line of lines) {
      const parts = line.trim().split(' ')
      if (parts.length >= 5) {
        // 从 bmc.kepler.xx 格式中提取 xx 部分作为服务名
        const fullServiceName = parts[0]
        let serviceName = fullServiceName
        
        // 检查是否是 bmc.kepler.xx 格式
        if (fullServiceName.startsWith('bmc.kepler.')) {
          const parts = fullServiceName.split('.')
          if (parts.length >= 3) {
            serviceName = parts.slice(2).join('.') // 取 bmc.kepler. 之后的所有部分
          }
        } else if (fullServiceName.includes('.')) {
          // 其他格式，取最后一段
          serviceName = fullServiceName.split('.').pop() || fullServiceName
        }
        
        const record: RPCRecord = {
          serviceName: serviceName,
          resourcePath: parts[1],
          resourceInterface: parts[2],
          method: parts[3],
          callCount: parseInt(parts[4]) || 1
        }
        records.push(record)
      }
    }
    
    return records
  }
  
  // 聚合RPC记录数据
  const aggregateRPCData = (records: RPCRecord[]): RPCRecord[] => {
    const aggregated = new Map<string, RPCRecord>()
    
    for (const record of records) {
      const key = `${record.serviceName}|${record.resourcePath}|${record.resourceInterface}|${record.method}`
      
      if (aggregated.has(key)) {
        const existing = aggregated.get(key)!
        existing.callCount += record.callCount
      } else {
        aggregated.set(key, { ...record })
      }
    }
    
    return Array.from(aggregated.values())
  }
  
  // 计算全局统计
  const calculateGlobalStats = () => {
    const totalCalls = rpcRecords.value.reduce((sum, record) => sum + record.callCount, 0)
    const activeServices = new Set(rpcRecords.value.map(record => record.serviceName)).size
    const activeMethods = rpcRecords.value.length
    
    globalStats.value = {
      totalCalls,
      activeServices,
      activeMethods
    }
  }
  
  // 计算服务排行榜
  const calculateServiceLeaderboard = () => {
    const serviceMap = new Map<string, ServiceStats>()
    
    for (const record of rpcRecords.value) {
      if (!serviceMap.has(record.serviceName)) {
        serviceMap.set(record.serviceName, {
          name: record.serviceName,
          totalCalls: 0,
          methods: []
        })
      }
      
      const service = serviceMap.get(record.serviceName)!
      service.totalCalls += record.callCount
      service.methods.push({
        serviceName: record.serviceName,
        resourcePath: record.resourcePath,
        resourceInterface: record.resourceInterface,
        method: record.method,
        callCount: record.callCount
      })
    }
    
    serviceLeaderboard.value = Array.from(serviceMap.values())
      .sort((a, b) => b.totalCalls - a.totalCalls)
  }
  
  // 计算热门方法排行榜
  const calculateHotMethods = () => {
    const totalCalls = rpcRecords.value.reduce((sum, record) => sum + record.callCount, 0)
    
    hotMethods.value = rpcRecords.value
      .sort((a, b) => b.callCount - a.callCount)
      .slice(0, 20)
      .map((record, index) => ({
        ...record,
        rank: index + 1,
        percentage: ((record.callCount / totalCalls) * 100).toFixed(2) + '%'
      }))
  }
  
  // 生成模拟趋势数据
  const generateTrendData = () => {
    const now = new Date()
    const data: TrendData[] = []
    
    for (let i = 23; i >= 0; i--) {
      const time = new Date(now.getTime() - i * 60 * 60 * 1000)
      const hour = time.getHours().toString().padStart(2, '0')
      const count = Math.floor(Math.random() * 10000) + 5000
      
      data.push({
        time: `${hour}:00`,
        count
      })
    }
    
    trendData.value = data
  }
  
  // 生成依赖关系数据
  const generateDependencyData = () => {
    const services = Array.from(new Set(rpcRecords.value.map(record => record.serviceName)))
    const nodes: DependencyNode[] = []
    const links: DependencyLink[] = []
    
    // 创建节点
    services.forEach((service, index) => {
      const totalCalls = rpcRecords.value
        .filter(record => record.serviceName === service)
        .reduce((sum, record) => sum + record.callCount, 0)
      
      nodes.push({
        id: service,
        name: service,
        value: totalCalls,
        category: index % 3
      })
    })
    
    // 创建链接（模拟服务间调用关系）
    for (let i = 0; i < services.length - 1; i++) {
      for (let j = i + 1; j < Math.min(i + 3, services.length); j++) {
        if (Math.random() > 0.5) {
          links.push({
            source: services[i],
            target: services[j],
            value: Math.floor(Math.random() * 1000) + 100
          })
        }
      }
    }
    
    dependencyNodes.value = nodes
    dependencyLinks.value = links
  }
  
  // 从文件系统加载RPC数据
  const loadRPCDataFromFiles = async (): Promise<RPCRecord[]> => {
    try {
      console.log('🚀 RPC数据加载: 开始加载流程')
      
      const fileDataStore = useFileDataStore()
      const workspaceStore = useWorkspaceStore()
      
      // 确保工作空间已初始化
      if (workspaceStore.workspaces.length === 0) {
        console.log('⏳ RPC数据加载: 工作空间未初始化，正在初始化...')
        await workspaceStore.initializeWorkspaces()
      }
      
      const currentWorkspace = workspaceStore.currentWorkspace
      
      console.log('📋 RPC数据加载: 工作空间信息', {
        hasWorkspace: !!currentWorkspace,
        workspaceId: currentWorkspace?.id,
        workspaceName: currentWorkspace?.name,
        totalWorkspaces: workspaceStore.workspaces.length,
        currentWorkspaceIdFromStore: workspaceStore.currentWorkspaceId
      })
      
      if (!currentWorkspace) {
        console.log('❌ RPC数据加载: 未找到当前工作空间')
        console.log('💡 提示: 请先创建或选择一个工作空间')
        return []
      }
      
      const fileData = fileDataStore.getFileData(currentWorkspace.id)
      console.log('📁 RPC数据加载: 文件数据信息', {
        hasFileData: !!fileData,
        fileDataLength: fileData?.length || 0,
        fileDataType: typeof fileData
      })
      
      if (!fileData) {
        console.log('❌ RPC数据加载: 当前工作空间没有文件数据')
        console.log('💡 提示: 请先上传并解压文件')
        return []
      }
      
      console.log('🔍 RPC数据加载: 开始从文件数据中查找 rpc_records.log 文件')
      console.log('📄 RPC数据加载: 文件数据预览（前500字符）:', fileData.substring(0, 500))
      
      const allRecords: RPCRecord[] = []
      
      // 使用新的查找方法：在 mdb_info.log 的同级目录中查找 rpc_records.log
      console.log('🎯 RPC数据加载: 使用智能查找方法 - 在 mdb_info.log 同级目录查找 rpc_records.log')
      
      try {
        const content = findRPCRecordsFromMdbDirectory(fileData)
        console.log('📋 RPC数据加载: findRPCRecordsFromMdbDirectory 结果:', {
          hasContent: !!content,
          contentLength: content?.length || 0,
          contentPreview: content ? content.substring(0, 200) : 'null'
        })
        
        if (content) {
          console.log('✅ RPC数据加载: 成功找到 rpc_records.log 文件')
          console.log('📄 RPC数据加载: 文件内容预览:', content.substring(0, 300))
          
          const records = parseRPCLogFile(content)
          console.log('🔧 RPC数据加载: parseRPCLogFile 结果:', {
            recordsCount: records.length,
            firstRecord: records[0] || 'none'
          })
          
          allRecords.push(...records)
          console.log(`📊 RPC数据加载: 解析到 ${records.length} 条记录`)
        } else {
          console.log('❌ RPC数据加载: 未找到 rpc_records.log 文件')
          console.log('💡 提示: 请确保工作空间中包含 mdb_info.log 文件，rpc_records.log 应该在同一目录下')
        }
      } catch (error) {
        console.warn('⚠️ RPC数据加载: 智能查找失败:', error)
        if (error instanceof Error) {
          console.warn('⚠️ RPC数据加载: 错误详情:', {
            message: error.message,
            stack: error.stack
          })
        }
      }
      
      console.log(`📈 RPC数据加载: 总共加载了 ${allRecords.length} 条原始记录`)
      console.log('📋 RPC数据加载: 原始记录样本:', allRecords.slice(0, 3))
      
      const aggregatedRecords = aggregateRPCData(allRecords)
      console.log(`📊 RPC数据加载: 聚合后得到 ${aggregatedRecords.length} 条记录`)
      console.log('📋 RPC数据加载: 聚合记录样本:', aggregatedRecords.slice(0, 3))
      
      return aggregatedRecords
    } catch (error) {
      console.error('❌ RPC数据加载: 加载过程中发生错误:', error)
      if (error instanceof Error) {
        console.error('❌ RPC数据加载: 错误详情:', {
          message: error.message,
          stack: error.stack,
          name: error.name
        })
      }
      return []
    }
  }
  
  // 生成模拟RPC数据（用于演示）
  const generateMockRPCData = (): RPCRecord[] => {
    const services = [
      'bmc.kepler.key_mgmt',
      'bmc.kepler.auth_service',
      'bmc.kepler.network_manager',
      'bmc.kepler.storage_controller',
      'bmc.kepler.power_management',
      'bmc.kepler.thermal_monitor',
      'bmc.kepler.event_handler',
      'bmc.kepler.user_service'
    ]
    
    const methods = [
      'RegisterKey',
      'ValidateKey',
      'DeleteKey',
      'GetStatus',
      'SetConfig',
      'GetInfo',
      'UpdateSettings',
      'ProcessEvent'
    ]
    
    const records: RPCRecord[] = []
    
    for (let i = 0; i < 100; i++) {
      const fullService = services[Math.floor(Math.random() * services.length)]
      const method = methods[Math.floor(Math.random() * methods.length)]
      
      // 从 bmc.kepler.xx 格式中提取 xx 部分作为服务名
      const serviceName = fullService.startsWith('bmc.kepler.') 
        ? fullService.split('.').slice(2).join('.')
        : fullService
      
      records.push({
        serviceName: serviceName,
        resourcePath: `/bmc/${fullService.split('.')[1]}/${fullService.split('.')[2]}Service`,
        resourceInterface: `${fullService}.${fullService.split('.')[2]}Service.${method}`,
        method: method,
        callCount: Math.floor(Math.random() * 1000) + 1
      })
    }
    
    return aggregateRPCData(records)
  }
  
  // 主要的数据加载函数
  const loadRPCData = async () => {
    try {
      // 首先尝试从文件系统加载真实数据
      let records = await loadRPCDataFromFiles()
      
      // 如果没有真实数据，使用模拟数据
      if (records.length === 0) {
        console.log('🔄 RPC数据加载: 未找到真实数据，使用模拟数据')
        console.log('💡 提示: 模拟数据仅用于演示，请确保 dump_info/AppDump/{component}/rpc_records.log 文件存在')
        records = generateMockRPCData()
        isUsingMockData.value = true
      } else {
        console.log('✅ RPC数据加载: 成功加载真实数据')
        isUsingMockData.value = false
      }
      
      rpcRecords.value = records
      
      console.log('📊 RPC数据加载: 开始计算统计数据')
      console.log('📋 RPC数据加载: rpcRecords.value长度:', rpcRecords.value.length)
      
      // 计算各种统计数据
      calculateGlobalStats()
      console.log('✅ 全局统计计算完成:', globalStats.value)
      
      calculateServiceLeaderboard()
      console.log('✅ 服务排行榜计算完成:', serviceLeaderboard.value.length, '个服务')
      console.log('📊 服务排行榜前3名:', serviceLeaderboard.value.slice(0, 3))
      
      calculateHotMethods()
      console.log('✅ 热门方法计算完成:', hotMethods.value.length, '个方法')
      
      generateTrendData()
      console.log('✅ 趋势数据生成完成:', trendData.value.length, '个数据点')
      
      generateDependencyData()
      console.log('✅ 依赖关系数据生成完成')
      
      console.log(`Loaded ${records.length} RPC records`)
    } catch (error) {
      console.error('Failed to load RPC data:', error)
      // 出错时使用模拟数据
      console.log('🔄 RPC数据加载: 出错，使用模拟数据')
      const records = generateMockRPCData()
      rpcRecords.value = records
      isUsingMockData.value = true
      
      console.log('📊 RPC数据加载: 开始计算统计数据（模拟数据）')
      calculateGlobalStats()
      console.log('✅ 全局统计计算完成（模拟）:', globalStats.value)
      
      calculateServiceLeaderboard()
      console.log('✅ 服务排行榜计算完成（模拟）:', serviceLeaderboard.value.length, '个服务')
      console.log('📊 服务排行榜前3名（模拟）:', serviceLeaderboard.value.slice(0, 3))
      
      calculateHotMethods()
      generateTrendData()
      generateDependencyData()
    }
  }
  
  // 刷新依赖关系数据
  const refreshDependencyData = () => {
    generateDependencyData()
  }
  
  // 执行自定义查询
  const executeCustomQuery = async (params: {
    serviceName?: string
    methodName?: string
    timeRange: string
  }) => {
    // 过滤数据
    let filteredRecords = rpcRecords.value
    
    if (params.serviceName) {
      filteredRecords = filteredRecords.filter(record => 
        record.serviceName === params.serviceName
      )
    }
    
    if (params.methodName) {
      filteredRecords = filteredRecords.filter(record => 
        record.method === params.methodName
      )
    }
    
    // 生成时间序列数据（模拟）
    const timeLabels: string[] = []
    const values: number[] = []
    
    const hours = params.timeRange === '1h' ? 1 : 
                 params.timeRange === '24h' ? 24 : 
                 params.timeRange === '7d' ? 24 * 7 : 24 * 30
    
    const interval = params.timeRange === '1h' ? 5 : // 5分钟间隔
                    params.timeRange === '24h' ? 60 : // 1小时间隔
                    params.timeRange === '7d' ? 60 * 24 : // 1天间隔
                    60 * 24 // 1天间隔
    
    const now = new Date()
    for (let i = hours - 1; i >= 0; i--) {
      const time = new Date(now.getTime() - i * interval * 60 * 1000)
      const label = params.timeRange === '1h' ? 
        `${time.getHours()}:${time.getMinutes().toString().padStart(2, '0')}` :
        params.timeRange === '24h' ?
        `${time.getHours()}:00` :
        `${time.getMonth() + 1}/${time.getDate()}`
      
      timeLabels.push(label)
      
      // 模拟数据点
      const baseValue = filteredRecords.reduce((sum, record) => sum + record.callCount, 0)
      const variance = Math.random() * 0.3 + 0.85 // 85%-115%的变化
      values.push(Math.floor(baseValue * variance / hours))
    }
    
    return {
      timeLabels,
      values
    }
  }
  
  return {
    // 状态
    rpcRecords,
    globalStats,
    trendData,
    serviceLeaderboard,
    hotMethods,
    dependencyNodes,
    dependencyLinks,
    isUsingMockData,
    
    // 计算属性
    allServices,
    allMethods,
    
    // 方法
    loadRPCData,
    refreshDependencyData,
    executeCustomQuery
  }
})